package org.hq.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;

/**
 * <h2>测试 - socket连接处理器</h2>
 * <p>
 *
 * </p>
 *
 * @author LiYang
 * @createTime 2022年07月19日 9:58 上午
 */
public class TestSocketHandler implements WebSocketHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(TestSocketHandler.class);

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        LOGGER.info("Test Socket 连接成功，sessionId：{}", session.getId());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        if (message instanceof TextMessage) {
            handlerTextMessage(session, (TextMessage) message);
        } else {
            LOGGER.error("Test Socket 消息处理失败，只接受 文本消息，sessionId：{}", session.getId());
        }
    }


    public void handlerTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        final String msg = message.getPayload();
        LOGGER.info("Test Socket 收到消息：{}", msg);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        LOGGER.error("Test Socket 处理异常，sessionId：{}, 异常原因：{}", session.getId(), exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        LOGGER.info("Test Socket 关闭，sessionId：{}", session.getId());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

